﻿Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Windows
Imports System.Xml
Imports Llama
Imports Plaice
Imports Set_DisplaySet
Imports rad2d = Ingr.RAD2D.Interop.RAD2D
Imports InteropPidAuto
Imports Telerik.WinControls.UI
Imports Telerik.WinControls.UI.Docking
Imports MyExcel = Microsoft.Office.Interop.Excel
Imports SPF.Client.Administration
Imports SPF.Client
Imports System.Threading
Imports Telerik.WinControls
Imports PlotDrawFromSha

Public Class RadForm1

    ''' <summary>
    ''' 连接pid的数据库，拿到plant structure目录，拿到保温文件路径，建立log文件等一系列初始操作
    ''' </summary>
    ''' <returns></returns>
    Public Function Initial_PIDConn() As String
        MyPIDConn.PlantName = DS.ProjectNumber
        MyPIDConn.ReadUserAndPs_in_PID(DS.SiteNode)
        Initial_PIDConn = MyPIDConn.ConnPID_admin(MyPIDConn.PIDIniDBType, MyPIDConn.PIDSite_Server, MyPIDConn.PIDSite_DBNAME, MyPIDConn.PIDDBSystemUser, MyPIDConn.PIDDBSystemPs)
        If Initial_PIDConn <> "" Then
            MessageBox.Show("运行ConnPID_admin时有误。" + vbNewLine + CallResult)
            Return Initial_PIDConn
        End If

        '拿plant structure目录
        SelectStr = <string>SELECT value FROM xxxSchemaName.T_PLANTSETTING T
            WHERE T.NAME = 'Plant Path'
                        </string>.Value

        Initial_PIDConn = MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.PIDPlant_User, SelectStr, dtCreate)
        If Initial_PIDConn <> "" Then
            strPlantPath = FindInfoInPlantSetting("Plant Path")
            Initial_PIDConn = ""
        Else
            strPlantPath = dtCreate(0)(0).ToString
        End If

        '拿保温文件InsulationSpec.isl路径
        SelectStr = <string>select value from xxxSchemaName.T_OPTIONSETTING t
            where t.name = 'Plant Insulation Specification File'
                                     </string>.Value
        dtCreate.Reset()
        Initial_PIDConn = MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr, dtCreate)
        If Initial_PIDConn <> "" Then
            sInsulFilePath = FindInfoInOptionManager("Plant Insulation Specification File")
            Initial_PIDConn = ""
        Else
            sInsulFilePath = dtCreate(0)(0).ToString
        End If

        '************190719   创建log文件夹
        If IO.Directory.Exists(sInsulFilePath.Replace("InsulationSpec.isl", "SNECLog")) Then
            'log文件夹存在
        Else
            'log文件夹不存在
            IO.Directory.CreateDirectory(sInsulFilePath.Replace("InsulationSpec.isl", "SNECLog"))
            If Not IO.Directory.Exists(sInsulFilePath.Replace("InsulationSpec.isl", "SNECLog")) Then
                MessageBox.Show("Log文件夹创建失败，不影响程序执行，但将无法记录日志信息")
            End If
        End If

        Return Initial_PIDConn
    End Function
    ''' <summary>
    ''' 初始化反向数据流这个window
    ''' </summary>
    Public Sub Initial_SpiToPid()
        RadGridView3.AllowAddNewRow = False : RadGridView4.AllowAddNewRow = False : RadGridView5.AllowAddNewRow = False : RadGridView6.AllowAddNewRow = False : RadGridView7.AllowAddNewRow = False
        RadGridView3.AllowDeleteRow = False : RadGridView4.AllowDeleteRow = False : RadGridView5.AllowDeleteRow = False : RadGridView6.AllowDeleteRow = False : RadGridView7.AllowDeleteRow = False
        'RadGridView3.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
        'RadGridView4.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
        'RadGridView5.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
        'RadGridView6.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
        'RadGridView7.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill

        RadGridView3.SelectionMode = GridViewSelectionMode.FullRowSelect : RadGridView4.SelectionMode = GridViewSelectionMode.FullRowSelect : RadGridView5.SelectionMode = GridViewSelectionMode.FullRowSelect : RadGridView6.SelectionMode = GridViewSelectionMode.FullRowSelect : RadGridView7.SelectionMode = GridViewSelectionMode.FullRowSelect
        RadGridView3.MultiSelect = True : RadGridView4.MultiSelect = True : RadGridView5.MultiSelect = True : RadGridView6.MultiSelect = True : RadGridView7.MultiSelect = True
        RadGridView3.ShowFilteringRow = True : RadGridView4.ShowFilteringRow = True : RadGridView5.ShowFilteringRow = True : RadGridView6.ShowFilteringRow = True : RadGridView7.ShowFilteringRow = True

        'RadGridView3.Enabled = True : RadGridView4.Enabled = True : RadGridView5.Enabled = True : RadGridView6.Enabled = True : RadGridView7.Enabled = True
        ' RadGridView3.AllowDragToGroup = False : RadGridView4.AllowDragToGroup = False : RadGridView5.AllowDragToGroup = False : RadGridView6.AllowDragToGroup = False : RadGridView7.AllowDragToGroup = False

        Dim checkBoxColumn As New GridViewCheckBoxColumn()
        checkBoxColumn.DataType = GetType(Boolean)
        checkBoxColumn.Name = "AllowUpdate"
        checkBoxColumn.FieldName = "AllowUpdate"
        checkBoxColumn.HeaderText = "更新"
        checkBoxColumn.EnableHeaderCheckBox = True '相当于全选
        checkBoxColumn.EditMode = EditMode.OnValueChange



        With RadGridView3
            .Columns.Add(checkBoxColumn)
            .Columns.Add("序号")
            .Columns.Add("位号")
            .Columns.Add("公称直径")
            .Columns.Add("公称直径（SPI）")
            .Columns.Add("执行机构")
            .Columns.Add("执行机构（SPI）")
            .Columns.Add("阀体形式")
            .Columns.Add("阀体形式（SPI）")
            .Columns.Add("图纸号")

        End With

        With RadGridView4
            .Columns.Add(checkBoxColumn)
            .Columns.Add("序号")
            .Columns.Add("位号")
            .Columns.Add("公称直径")
            .Columns.Add("公称直径（SPI）")
            .Columns.Add("仪表类型")
            .Columns.Add("仪表类型（SPI）")
            .Columns.Add("图纸号")
        End With

        With RadGridView5
            .Columns.Add(checkBoxColumn)
            .Columns.Add("序号")
            .Columns.Add("位号")
            .Columns.Add("分支管")
            .Columns.Add("分支管（SPI）")
            .Columns.Add("图纸号")
        End With

        With RadGridView6
            .Columns.Add(checkBoxColumn)
            .Columns.Add("序号")
            .Columns.Add("位号")
            .Columns.Add("分支管")
            .Columns.Add("分支管（SPI）")
            .Columns.Add("图纸号")
        End With

        With RadGridView7
            .Columns.Add(checkBoxColumn)
            .Columns.Add("序号")
            .Columns.Add("位号")
            .Columns.Add("分支管")
            .Columns.Add("分支管（SPI）")
            .Columns.Add("图纸号")
        End With
        Me.反向数据流.Hide()
    End Sub

    Private Sub RadForm1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Me.Text = "宁波工程公司 SPPID 外部工具 (" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + ")"
        Try
            If System.Windows.Forms.Application.StartupPath.Length > 128 Then
                MessageBox.Show("工具所在的路径太深（超过了128个字符），请改到浅一点的路径上。再重新使用。")
                System.Windows.Forms.Application.Exit()
            End If

            Try
                DS = New LMADataSource           '尽量少New，只用一个，耗时
            Catch ex As Exception
                MessageBox.Show("请确保本机上安装有SmartPlant P&ID，程序将退出。" & vbNewLine & ex.Message)
                Me.Close()
            End Try

            Me.RadLabelElement1.Text = "当前连接的数据库: " + DS.SiteNode     '当前激活的工厂

            '打开程序当前路径下的config.txt文件
            '内容就是楼主贴出来的
            Try
                If IO.File.Exists(System.Windows.Forms.Application.StartupPath + "/RecentlySiteAndPlant.ini") Then
                    Dim reader As TextReader = File.OpenText(System.Windows.Forms.Application.StartupPath + "/RecentlySiteAndPlant.ini")
                    Dim line As String = reader.ReadLine() '读第一行
                    While line <> ""
                        Debug.Print(line)
                        Dim newButton As New Telerik.WinControls.UI.RadMenuItem()
                        newButton.Text = line
                        RadMenuItem26.Items.Add(newButton)   '动态按钮
                        AddHandler newButton.Click, AddressOf Me.ChangeSiteAndPlant   '点击事情的委托

                        line = reader.ReadLine() '读下一行
                    End While
                    reader.Close()
                    reader = Nothing
                End If

            Catch ex As Exception

            End Try



            CallResult = Initial_PIDConn()
            If CallResult <> "" Then
                MessageBox.Show(CallResult)
                Me.Close()
                Exit Sub
            End If
            LoadDrawing(True)


        Catch ex As Exception
            MessageBox.Show("工具初始化有误，程序将退出。" & vbNewLine & ex.Message)
            Me.Close()
        End Try
        Initial_EDE()
        Initial_SpiToPid()
    End Sub

    ''' <summary>
    ''' 用于快速切换site的按钮，统一触发点击事件的委托
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub ChangeSiteAndPlant(ByVal sender As Object, ByVal e As EventArgs)
        Dim btn As RadMenuItem : Dim siteInfor As String
        btn = CType(sender, RadMenuItem)
        siteInfor = btn.Text


        If DS.SiteNode = siteInfor.Split("@")(1) And DS.ProjectNumber = siteInfor.Split("@")(2) Then
            Exit Sub
        End If

        DS.SiteNode = siteInfor.Split("@")(1) : DS.ProjectNumber = siteInfor.Split("@")(2) : MyPIDConn.PlantName = siteInfor.Split("@")(2)
        Me.RadLabelElement1.Text = "当前连接的数据库: " + DS.SiteNode     '当前激活的工厂
        Open_Database.SwitchSPEMINI(DS.SiteNode, MyPIDConn.PlantName)
        CallResult = Initial_PIDConn()
        If CallResult <> "" Then
            MessageBox.Show(CallResult)
            Exit Sub
        End If

        LoadDrawing(True)
        Initial_EDE()

        Dim proc As Process() = System.Diagnostics.Process.GetProcessesByName("drawingmanagerexe")
        '得到名为excel进程个数，全部关闭
        Dim exePath As String = ""
        For i = 0 To proc.Length - 1
            Debug.Print(proc(i).ProcessName)
            exePath = proc(i).MainModule.FileName
            proc(i).Kill()

        Next
        proc = Nothing
        If exePath = "" Then
            Dim Key2 As Microsoft.Win32.RegistryKey
            Key2 = My.Computer.Registry.LocalMachine.
                OpenSubKey("SOFTWARE\WOW6432Node\Intergraph\Applications\SmartPlantPID.Application\Setup")
            exePath = Key2.GetValue("InstallPath") + "\bin\drawingmanagerexe.exe"
        End If
        Process.Start(exePath)

    End Sub


    Private Sub RadMenuItem6_Click(sender As Object, e As EventArgs) Handles RadMenuItem6.Click
        With Open_Database
            .RadListControl1.Items.Clear()
            SelectStr = <string>
select t.name,t.description,t.path,t2.username,t2.password,t2.sp_schema_type 
from xxxSchemaName.t_rootitem t 
join xxxSchemaName.t_db_data t2 on t.sp_id=t2.sp_rootitemid
where t.plantgrouptypename='Plant' and t2.sp_schema_type in ('SPAPLANT')
</string>.Value
            dtCreate.Reset()
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDSite_DBNAME, MyPIDConn.PIDSite_User, SelectStr, dtCreate)
            For i = 0 To dtCreate.Rows.Count - 1  '在OraConn或SQLConn中，查询到的所有的Plant
                .RadListControl1.Items.Add(dtCreate.Rows(i)(0).ToString)
                '.RadListControl1.Items(i) = dtCreate.Rows(i)(0)
            Next

            .Show()
            'Me.Enabled = False
            .TopMost = True
            .Text = "当前数据库:" + DS.SiteNode           'ini所在目录
        End With
    End Sub
    ''' <summary>
    ''' 遍历
    ''' </summary>
    ''' <param name="curNode"></param>

    Sub LoopTree(curNode As RadTreeNode, checked As Boolean)
        If curNode.Level = MaxDepth And checked = True Then
            ' e.Node.Name
            For Each subnode As RadTreeNode In curNode.Nodes
                subnode.Checked = checked
            Next

            curNode.ExpandAll()   '自动展开
        ElseIf curNode.Level = MaxDepth And checked = False Then
            ' e.Node.Name+
            For Each subnode As RadTreeNode In curNode.Nodes
                subnode.Checked = checked
            Next
            If curNode.Expanded = True Then   '防止本来就展开,但是unit节点未选中的情况下。此时选中unit节点，反而收缩回去了
                curNode.Toggle()
            End If
        Else
            '非最后一级
            For Each subnode As RadTreeNode In curNode.Nodes
                subnode.Checked = checked
                LoopTree(subnode, curNode.Checked)
            Next
        End If
    End Sub

    Private Sub RadTreeView1_NodeCheckedChanged(sender As Object, e As TreeNodeCheckedEventArgs) Handles RadTreeView1.NodeCheckedChanged
        LoopTree(e.Node, e.Node.Checked)
        'If e.Node.Level = MaxDepth And e.Node.Checked = True Then
        '    ' e.Node.Name
        '    For Each subnode As RadTreeNode In e.Node.Nodes
        '        subnode.Checked = e.Node.Checked
        '    Next

        '    e.Node.ExpandAll()   '自动展开
        'ElseIf e.Node.Level = MaxDepth And e.Node.Checked = False Then
        '    ' e.Node.Name+
        '    For Each subnode As RadTreeNode In e.Node.Nodes
        '        subnode.Checked = e.Node.Checked
        '    Next
        '    If e.Node.Expanded = True Then   '防止本来就展开,但是unit节点未选中的情况下。此时选中unit节点，反而收缩回去了
        '        e.Node.Toggle()
        '    End If
        'End If
    End Sub

    Private Sub RadMenuItem17_Click(sender As Object, e As EventArgs) Handles RadMenuItem17.Click
        Export_Inconsistency()
    End Sub

    Private Sub RadMenuItem16_Click(sender As Object, e As EventArgs) Handles RadMenuItem16.Click
        Dim intResult As Integer
        intResult = MessageBox.Show("将执行开图，以放置Assembly。" + vbNewLine + "为加快速度，请先打开P&ID主程序（draft.exe）" +
                                    vbNewLine + "放置以Unit为单位进行批量操作。", "Warning！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
        UnitCol.Clear() : DrawingCol.Clear()
        LoopTreeNode(Me.RadTreeView1.Nodes.Item(0), DrawingCol, UnitCol)
        If intResult = DialogResult.OK Then
            If UnitCol.Count <> 1 Then
                MessageBox.Show("请从左侧目录树中选择一个UNIT的节点及需要的图纸。UNIT多选或不选都不可以。")
            Else
                MessageBox.Show("请知晓放置的条件：" +
                                vbNewLine + "1.空图纸已经在Drawing Manager中建立了" +
                                vbNewLine + "2.当前Unit的空图纸，其名字里需要包含Assembly文件夹的名字")
                Dim UnitID As String = UnitCol.Item(0)
                Dim dtDrawing As New DataTable
                '拿这个unit下的所有图纸
                SelectStr = String.Format("select sp_id,name from xxxSchemaName.t_drawing where sp_plantgroupid='{0}'", UnitID)
                MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr, dtDrawing)
                Dim RefRootFolder As String = FindInfoInOptionManager("Catalog Explorer root path")
                Dim OpenAssemblyFolder As New FolderBrowserDialog With {
                    .SelectedPath = RefRootFolder
                }
                If OpenAssemblyFolder.ShowDialog() = DialogResult.OK And Not (OpenAssemblyFolder.SelectedPath Is Nothing) Then

                    '拿配置文件
                    Dim XMLPath As String = System.Windows.Forms.Application.StartupPath & "配置文件" & "\Config.xml"
                    Dim oRootNode As XmlNode : Dim xmlItemTagFormat As New XmlDocument
                    If Not IO.File.Exists(XMLPath) Then
                        MessageBox.Show("读取config.xml错误。")
                        Exit Sub
                    Else
                        If IsNothing(oRootNode) Then
                            xmlItemTagFormat.Load(XMLPath)
                            oRootNode = xmlItemTagFormat.SelectSingleNode("PIDToolConfiguration")
                        Else
                            '避免多次
                        End If

                        '这一段就是读取常规的属性，SPIDATA这个章节里的。
                        Dim oAssemblyNode As XmlNode : Dim MyFormat As String = "" : Dim X As Double = 0.0# : Dim Y As Double = 0.0#
                        oAssemblyNode = oRootNode.SelectSingleNode("PlaceAssembly")
                        If Not oAssemblyNode Is Nothing Then
                            MyFormat = oAssemblyNode.SelectSingleNode("DrawingName").Attributes("Format").Value
                            Try
                                X = Convert.ToDouble(oAssemblyNode.SelectSingleNode("Coordinate").Attributes("X").Value)
                                Y = Convert.ToDouble(oAssemblyNode.SelectSingleNode("Coordinate").Attributes("Y").Value)
                            Catch
                                MessageBox.Show("读取config.xml->PlaceAssembly->X Y属性错误。")
                                Exit Sub
                            End Try
                            MyFormat = MyFormat.Replace("FolderName", Mid(OpenAssemblyFolder.SelectedPath, InStrRev(OpenAssemblyFolder.SelectedPath, "\") + 1))
                            '遍历assembly下的所有.pid文件
                            Dim objPIDAutoApp As InteropPidAuto.Application
                            Dim objPIDADrawing As InteropPidAuto.Drawing
                            Dim mFileInfo As System.IO.FileInfo
                            Dim mDirInfo As New System.IO.DirectoryInfo(OpenAssemblyFolder.SelectedPath)

                            Try
                                'On Error GoTo Failed
                                objPIDAutoApp = CreateObject("pidautomation.Application")   '创建draft.exe进程
                                'objPIDAutoApp.Visible = False
                            Catch
                                MessageBox.Show("无法打开SPP&ID，请检查许可、软件是否被莫名查杀等")
                                Exit Sub

                            End Try

                            Try
                                '是根据drawing去找assembly，还是反过来？   应该是反过来，assembly找起来不方便。

                                For Each mFileInfo In mDirInfo.GetFiles("*.pid")
                                    Debug.Print(mFileInfo.Name)   '不需要fullname
                                    '去找drawing
                                    For Each DrawFound As DataRow In dtDrawing.Select("NAME LIKE '%" + MyFormat.Replace("AssemblyName", mFileInfo.Name.Replace(".pid", "")) + "%'")
                                        '查到多个图纸怎么办？
                                        'Me.RadProgressBarElement1.Text = mFileInfo.Name
                                        '放置assembly
                                        Try
                                            objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(DrawFound("NAME"))
                                        Catch  '如果设置为后台开，好像就不会抱错了
                                            Try
                                                objPIDADrawing = objPIDAutoApp.ActiveDrawing   '.NET上，上一句运行后，虽然图纸能打开，但是会抱错，所以加了这一句
                                            Catch ex As Exception
                                                objPIDAutoApp = Nothing
                                                objPIDAutoApp = CreateObject("pidautomation.Application")
                                                objPIDAutoApp.Visible = False
                                                objPIDADrawing = objPIDAutoApp.ActiveDrawing
                                            End Try
                                        End Try

                                        If objPIDADrawing Is Nothing Then
                                            Writelog(DrawFound("NAME") + "    图纸未能打开", "OpenDrawing（PlaceAssembly）")
                                        Else
                                            Dim objPlacement As Placement = New Placement
                                            Dim objItems As LMAItems
                                            objItems = objPlacement.PIDPlaceAssembly(mFileInfo.FullName.Replace(RefRootFolder, ""), X, Y)
                                            'Dim blnPlaceOK As Boolean = False
                                            'If objItems.Count > 0 Then
                                            '    blnPlaceOK = True
                                            'End If
                                            Try
                                                objPIDADrawing.CloseDrawing(True)
                                            Catch ex As Exception
                                                Writelog(DrawFound("NAME") + "    图纸打开,但未正常关闭", "OpenDrawing")
                                            End Try

                                            Writelog(DrawFound("NAME") + "    图纸打开,并正确放置Assembly，然后关闭", "OpenDrawing")
                                        End If
                                    Next
                                Next

                            Catch ex As System.IO.DirectoryNotFoundException
                                Debug.Print("目录没找到：" + ex.Message)
                            End Try

                            objPIDADrawing = Nothing
                            'objPIDAutoApp.Visible = True



                        Else
                            MessageBox.Show("读取config.xml下的PlaceAssembly节点错误。")
                        End If

                    End If
                    dtDrawing = Nothing

                End If
            End If

        End If
        Dim audit As New audit(DS.ProjectNumber, "Assembly复用", "V1.0")
        audit.Add()
        audit = Nothing
        MessageBox.Show("批量自动放置Assembly结束。")
    End Sub

    Private Sub RadMenuItem15_Click(sender As Object, e As EventArgs) Handles RadMenuItem15.Click
        '步骤1，选图纸
        Dim objDrawings As New LMDrawings
        'Dim DrawingList As DockLeft = FormList.Item(0)   '靠arraylist作为中转，否则读不到mainform下的图纸目录树的form
        Try
            GetDwgCol(DS, DrawingCol, objDrawings)
            If DrawingCol.Count = 0 Then
                MessageBox.Show("一张图纸都没选")
                Exit Sub
            End If
        Catch
            MessageBox.Show("加载图纸列表失败")
            Exit Sub
        End Try
        Dim audit As New audit(DS.ProjectNumber, "图纸数据完整性检查", "V1.0")
        audit.Add()
        audit = Nothing
        '步骤1-1，创建excel
        Dim objExcelApp As MyExcel.Application
        Dim objExcelBook As MyExcel.Workbook
        Dim objExcelSheetOverview As MyExcel.Worksheet
        Dim objExcelSheetTypeName As MyExcel.Worksheet

        objExcelApp = New MyExcel.Application
        objExcelApp.DisplayAlerts = False
        objExcelBook = objExcelApp.Workbooks.Add()

        objExcelSheetOverview = objExcelBook.Sheets(1)
        objExcelSheetOverview.Name = "总览"
        objExcelSheetOverview.Cells(1, 1) = "Name"
        objExcelSheetOverview.Cells(1, 2) = "DwgNo"
        objExcelSheetOverview.Cells(1, 3) = "Goal"
        objExcelSheetOverview.Cells(1, 4) = "Pass"

        'Sub_start(Me, "读取xml配置文件")

        '步骤2，读xml的属性配置
        Dim xmlAttrQualityCheck As New Xml.XmlDocument
        Dim oRootNode As Xml.XmlNode
        Dim oAttGroupNode As Xml.XmlNode
        Dim PassValue As Integer
        xmlAttrQualityCheck.Load(FindInfoInOptionManager("Catalog Explorer root path").Replace("Symbols", "ObjectAttrValidation.xml"))
        oRootNode = xmlAttrQualityCheck.SelectSingleNode("ObjectConfiguration")
        PassValue = CInt(oRootNode.Attributes("PassValue").Value)
        Dim EntityCol As ArrayList = New ArrayList
        EntityCol.Clear()
        Dim EntityPassValueCol As ArrayList = New ArrayList
        EntityPassValueCol.Clear()
        Dim PropCol As ArrayList = New ArrayList
        PropCol.Clear()
        Dim FilterCol As ArrayList = New ArrayList
        FilterCol.Clear()
        Dim LMAFilterCol As ArrayList = New ArrayList
        LMAFilterCol.Clear()
        Dim objCol As Object
        For Each oTypeNode As Xml.XmlNode In oRootNode.ChildNodes
            '读入每一类对象的属性
            Dim PropsAll As String = ""
            Dim Props As String()

            Try
                FilterCol.Add(oTypeNode.Attributes("Filter").Value)

                If oTypeNode.Attributes("IsSpecial").Value = "No" Then
                    '普通
                    oAttGroupNode = oTypeNode.SelectSingleNode("General")
                ElseIf oTypeNode.Attributes("IsSpecial").Value = "Yes" Then
                    '特殊   
                    '暂不考虑
                    oAttGroupNode = oTypeNode.SelectSingleNode("Special")
                Else
                    oAttGroupNode = oTypeNode.SelectSingleNode("General")
                End If
                For Each oAttNode As Xml.XmlNode In oAttGroupNode.ChildNodes '每一个AttributeFormat的节点
                    PropsAll += oAttNode.Attributes("Name").Value & "|" &
                                oAttNode.Attributes("Weight").Value & "|" &
                                oAttNode.Attributes("Format").Value & "|" &
                                oAttNode.Attributes("IsRequired").Value & "@"
                Next
                PropsAll = Mid(PropsAll, 1, PropsAll.Length - 1)
                Props = PropsAll.Split("@")
                PropCol.Add(Props)


                Select Case oTypeNode.Attributes("ITEMTYPE").Value.ToString
                    Case "Instrument"
                        objCol = New LMInstruments
                    Case "Equipment"
                        objCol = New LMEquipments
                    Case "PipeRun"
                        objCol = New LMPipeRuns
                    Case "InstrLoop"
                        objCol = New LMInstrLoops
                    Case "Nozzle"
                        objCol = New LMNozzles
                    Case "PipingComp"
                        objCol = New LMPipingComps
                    Case Else
                        GoTo NextNode
                End Select
                Try
                    EntityCol.Add(objCol)
                    EntityPassValueCol.Add(oTypeNode.Attributes("PassValue").Value)
                    objExcelSheetTypeName = objExcelBook.Sheets.Add
                    If oTypeNode.Attributes("Filter").Value = "" Then
                        objExcelSheetTypeName.Name = oTypeNode.Attributes("ITEMTYPE").Value.ToString
                    Else

                        objExcelSheetTypeName.Name = oTypeNode.Attributes("ITEMTYPE").Value.ToString & "|" & oTypeNode.Attributes("Filter").Value
                    End If

                    objExcelSheetTypeName.Cells(1, 1) = "P&ID"
                    objExcelSheetTypeName.Cells(1, 2) = "SPID"
                    objExcelSheetTypeName.Cells(1, 3) = "PASS"
                    For i = 0 To Props.Length - 1
                        objExcelSheetTypeName.Cells(1, i + 4) = Props(i)
                    Next
                Catch
                End Try
NextNode:
            Catch
                '该Entity节点设置不对
            End Try
        Next

        Dim MyRange4Fill(,) As String
        ReDim MyRange4Fill(objDrawings.Count - 1, 4 - 1)

        'Sub_end(Me)
        'Sub_start(Me, "读取工厂已有的过滤器")
        '步骤2-2,读出已有的filters
        Dim inx As Integer
        LMAFilterCol = FilterCol.Clone()
        Dim objFilter As LMAFilter
        For Each objFilter In DS.Filters
            Debug.Print(objFilter.Name)
            inx = 0
            Do While inx < FilterCol.Count
                If objFilter.Name = FilterCol(inx) Then
                    LMAFilterCol.RemoveAt(inx)
                    LMAFilterCol.Insert(inx, objFilter)

                    GoTo NextFilter
                End If
                If FilterCol(inx).ToString.Trim <> "" Then
                    LMAFilterCol.RemoveAt(inx)
                    FilterCol.RemoveAt(inx)
                    EntityCol.RemoveAt(inx)
                    PropCol.RemoveAt(inx)
                    inx -= 1
                End If
                inx += 1
            Loop

NextFilter:
        Next
        'Sub_end(Me)

        'Sub_start(Me, "开始读取图纸")
        '步骤3，循环图纸
        Dim RegexResult As Boolean
        Dim DwgIndex = 0
        Dim objAttr As LMAAttribute
        Dim objFilterAll As LMAFilter
        Dim objFilter2 As LMAFilter


        For Each objDrawing As LMDrawing In objDrawings

            Dim DrawingObjCount As Integer = 0
            Dim DrawingGoal As Integer = 0

            'Me.RadProgressBarElement1.Text = EntityCol.Count - 1

            '步骤4，循环每一类对象
            For j = 0 To EntityCol.Count - 1

                'Me.RadProgressBarElement1.Text = j
                System.Windows.Forms.Application.DoEvents()

                objFilter = New LMAFilter


                With objFilter
                    .ItemType = EntityCol.Item(j).typename.ToString 'LMEquipments 的 TypeName 就是 Equipment

                    .Criteria.AddNew("1")
                    .Criteria.Item("1").SourceAttributeName = "Representation.Drawing.Name"
                    .Criteria.Item("1").ValueAttribute = objDrawing.Name
                    .Criteria.Item("1").Operator = "="
                End With

                If FilterCol.Item(j) <> "" Then
                    objExcelSheetTypeName = objExcelBook.Sheets.Item(objFilter.ItemType.ToString & "|" & FilterCol.Item(j))
                    'xml中有过滤器，就组合一个复杂的过滤器
                    objFilter2 = New LMAFilter
                    objFilter2 = LMAFilterCol.Item(j)
                    objFilterAll = New LMAFilter

                    objFilterAll.FilterType = 1 '1 for compound filter, 0 for simple filter
                    objFilterAll.ChildLMAFilters.Add(objFilter)
                    objFilterAll.ChildLMAFilters.Add(objFilter2)
                    objFilterAll.Conjunctive = True

                    EntityCol.Item(j).clear()
                    EntityCol.Item(j).COLLECT(DS, Filter:=objFilterAll)
                Else
                    objExcelSheetTypeName = objExcelBook.Sheets.Item(objFilter.ItemType.ToString)
                    'xml中没指定过滤器，就只过滤当前图纸
                    EntityCol.Item(j).clear()
                    EntityCol.Item(j).COLLECT(DS, Filter:=objFilter)
                End If


                Dim MyRange4Fill4Obj(,) As String
                ReDim MyRange4Fill4Obj(EntityCol.Item(j).Count - 1, PropCol.Item(j).length - 1 + 3)   '+1是额外多了SPID一列

                '步骤4，循环每一类对象下的每个对象
                Dim IfRequiredFail As Boolean
                Dim ObjIndex = 0
                Dim CurSheetUsedRows = objExcelSheetTypeName.UsedRange.Rows.Count
                For Each obj As Object In EntityCol.Item(j)



                    IfRequiredFail = True
                    'obj可能是LMPipeRun，可能是LMInstrument
                    Dim ObjGoal As Integer = 0
                    MyRange4Fill4Obj(ObjIndex, 0) = obj.ID ''''''''''
                    MyRange4Fill4Obj(ObjIndex, 1) = objDrawing.Name ''''''''''
                    '步骤5，循环属性

                    For k = 0 To PropCol.Item(j).length - 1

                        'Debug.Print(obj.attributes(PropCol.Item(j)(k).split("|")(0)).value.ToString)
                        '每个属性是否Pass
                        Try
                            objAttr = obj.attributes(PropCol.Item(j)(k).split("|")(0))
                            If IsDBNull(objAttr.Value) Then
                                '属性不加权
                                MyRange4Fill4Obj(ObjIndex, k + 3) = ""
                                If PropCol.Item(j)(k).split("|")(3) = "Yes" Then
                                    '强制需要填写或满足正则，但由于属性没PASS，整个对象就失败了
                                    objExcelSheetTypeName.Range(objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 4 + k),
                                                                    objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 4 + k)).Interior.ColorIndex = 7 '亮紫
                                    IfRequiredFail = False
                                End If
                            ElseIf objAttr.Value = "" Then
                                '属性不加权
                                MyRange4Fill4Obj(ObjIndex, k + 3) = objAttr.Value
                                If PropCol.Item(j)(k).split("|")(3) = "Yes" Then
                                    '强制需要填写或满足正则，但由于属性没PASS，整个对象就失败了
                                    objExcelSheetTypeName.Range(objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 4 + k),
                                                                    objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 4 + k)).Interior.ColorIndex = 7 '亮紫
                                    IfRequiredFail = False
                                End If
                            Else
                                If PropCol.Item(j)(k).split("|")(2) = "" Then  '属性节点里的Format属性,即正则表达式的匹配公式
                                    '按有值无值来简单判断
                                    '属性加权
                                    ObjGoal += CInt(PropCol.Item(j)(k).split("|")(1))
                                    MyRange4Fill4Obj(ObjIndex, k + 3) = objAttr.Value
                                Else
                                    '按正则表达式来
                                    RegexResult = Regex.Match(objAttr.Value, PropCol.Item(j)(k).split("|")(2)).Success
                                    If RegexResult Then
                                        '属性加权  
                                        ObjGoal += CInt(PropCol.Item(j)(k).split("|")(1))
                                        MyRange4Fill4Obj(ObjIndex, k + 3) = objAttr.Value
                                    Else
                                        '属性不加权
                                        MyRange4Fill4Obj(ObjIndex, k + 3) = objAttr.Value
                                        If PropCol.Item(j)(k).split("|")(3) = "Yes" Then
                                            '强制需要填写或满足正则，但由于属性没PASS，整个对象就失败了

                                            objExcelSheetTypeName.Range(objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 4 + k),
                                                                    objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 4 + k)).Interior.ColorIndex = 7 '亮紫
                                            IfRequiredFail = False
                                        Else
                                            objExcelSheetTypeName.Range(objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 4 + k),
                                                                   objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 4 + k)).Interior.ColorIndex = 12 '深黄
                                        End If


                                    End If
                                End If
                            End If

                        Catch
                            '对象读取某个属性时，报错
                        End Try

                    Next
                    If Not IfRequiredFail Then
                        '因为IsRequired的属性没有达到要求
                        ObjGoal = 0
                    End If
                    '每个对象是否Pass
                    If ObjGoal < CInt(EntityPassValueCol.Item(j).ToString) Then
                        '对象不加权,NOT PASS
                        objExcelSheetTypeName.Range(objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 3),
                                                    objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex + 1, 3)).Interior.ColorIndex = 3 '红色
                        MyRange4Fill4Obj(ObjIndex, 2) = "NOT Pass" ''''''''''
                    Else
                        '对象加权,PASS
                        MyRange4Fill4Obj(ObjIndex, 2) = "Pass" ''''''''''
                        DrawingGoal += 1
                    End If
                    DrawingObjCount += 1
                    ObjIndex += 1
                Next
                objExcelSheetTypeName.Range(objExcelSheetTypeName.Cells(CurSheetUsedRows + 1, 1),
                                            objExcelSheetTypeName.Cells(CurSheetUsedRows + ObjIndex, 3 + PropCol.Item(j).length)).Value = MyRange4Fill4Obj
                MyRange4Fill4Obj = Nothing
            Next
            '步骤6，加权，统计，输出一个excel
            'Excel有一个总览，每张图纸Pass否
            '针对每张图纸，都
            If DrawingGoal * 100 < DrawingObjCount * PassValue Then
                '以对象作为一个加分项来做好了
                '图纸没有Pass
                MyRange4Fill(DwgIndex, 3) = "NOT Pass"
                objExcelSheetOverview.Range(objExcelSheetOverview.Cells(DwgIndex + 2, 4),
                                            objExcelSheetOverview.Cells(DwgIndex + 2, 4)).Interior.ColorIndex = 3

            Else
                '图纸Pass
                MyRange4Fill(DwgIndex, 3) = "Pass"
            End If
            MyRange4Fill(DwgIndex, 0) = objDrawing.Name.ToString
            MyRange4Fill(DwgIndex, 1) = objDrawing.Attributes("DrawingNumber").Value.ToString
            MyRange4Fill(DwgIndex, 2) = (DrawingGoal / DrawingObjCount * 100).ToString & "%"


            DwgIndex += 1
        Next
        objExcelSheetOverview.Range(objExcelSheetOverview.Cells(1 + 1, 1),
                                    objExcelSheetOverview.Cells(objDrawings.Count + 1, 4)).Value = MyRange4Fill
        'Sub_end(Me)
        objExcelApp.Visible = True
        objDrawings = Nothing
    End Sub



    Private Sub RadMenuItem11_Click(sender As Object, e As EventArgs) Handles RadMenuItem11.Click
        Dim intResult As Integer
        Dim objDrawings As LMDrawings
        Dim objHistories As LMHistories
        intResult = MessageBox.Show("将执行开图，以刷新Title Block。" + vbNewLine + "为加快速度，请先打开P&ID主程序（draft.exe）", "Warning！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
        DrawingCol.Clear() : UnitCol.Clear()
        LoopTreeNode(Me.RadTreeView1.Nodes.Item(0), DrawingCol, UnitCol)
        If intResult = DialogResult.OK Then
            'Sub_start(Me, "")
            Dim AutoGap As Interopautogapall.AutoGapAllCmd = New Interopautogapall.AutoGapAllCmd
            Dim objPID2d As Ingr.RAD2D.Interop.RAD2D.Application
            Dim objPIDAutoApp As InteropPidAuto.Application
            Dim objPIDADrawing As InteropPidAuto.Drawing
            objDrawings = New LMDrawings
            'Dim LastOpenTime As String = ""
            'Dim LastRevTime As String
            objHistories = New LMHistories

            Dim DwgIDs As String = ""
            If DrawingCol.Count = 0 Then
                'Sub_end(Me)
                MessageBox.Show("未选中任一图纸")
                Exit Sub
            End If
            GetDwgCol(DS, DrawingCol, DwgIDs)
            SelectStr = <string>
    select t.name
    from xxxSchemaName.t_drawing t
    where t.sp_id in (xxxDWGIDS)
                        </string>.Value
            SelectStr = Replace(SelectStr, "xxxDWGIDS", DwgIDs)
            dtCreate.Reset()
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr, dtCreate)
            'objDrawings.Collect(DS) '不要全部的图纸，只要选中的就行了
            Try
                'On Error GoTo Failed
                objPIDAutoApp = CreateObject("pidautomation.Application")
                objPIDAutoApp.Visible = False


            Catch
                MessageBox.Show("无法打开SPP&ID，请检查许可、软件是否被莫名查杀等")
                Exit Sub

            End Try

            Dim IntCount As Integer = 0
            Dim DrawingOpenCount As Integer = 0
            'ProgressBar1.Maximum = dtCreate.Rows.Count
            'ProgressBar1.Minimum = 0
            'DS.BeginTransaction()
            'Me.TopMost = True
            'For Each objDrawing As LMDrawing In objDrawings
            For i = 0 To dtCreate.Rows.Count - 1

                'If objDrawing.Attributes("Name").Value = "00PID0001" Then
                '    Module1.insul3 = 1
                'End If
                'My.Application.DoEvents()
                'LastRev = New LMAItem    ’这个放在这里居然会抱错

                If 0 Then   '之前的代码，根据时间判断应不应该打开，但是如果是按照选择图纸来的话，没必要了，直接打开完事了
                    'Try
                    '    LastRevTime = objDrawing.Revisions.Nth(objDrawing.Revisions.Count).Attributes("SP_RevisionDate").Value
                    'Catch
                    '    '如果图纸没有revision的话
                    '    Writelog(objDrawing.Attributes("Name").Value + "    图纸因没有Revision，无须打开", "OpenDrawing")
                    '    GoTo nextFOR
                    'End Try
                    'objHistories = objDrawing.Histories
                    'For Each objhi As LMHistory In objHistories   '也就只会循环一次
                    '    LastOpenTime = objhi.Attributes.Item("Timestamp").Value   '这个属性不在图纸上，而是在history上
                    'Next

                    'If objDrawing.Attributes("ItemStatus").Index = 1 And DateDiff(DateInterval.Minute, CDate(LastOpenTime), CDate(LastRevTime)) > 0 Then '1 stands for Active,同时打开时间比Revise时间新
                    '    'DateDiff, <0 stands 1的时间戳更晚, >0 stands 2的时间戳更晚
                    '    DrawingOpenCount = DrawingOpenCount + 1
                    '    Try
                    '        '属性更新，后面再打开图纸  '打开图纸的同时，把属性传递下。Revision给Title Block Revision。
                    '        objDrawing.Attributes("Revision").Value = objDrawing.Revisions.Nth(objDrawing.Revisions.Count).Attributes("SP_MajorRevisionNumber").Value +
                    '                                  objDrawing.Revisions.Nth(objDrawing.Revisions.Count).Attributes("SP_MinorRevisionNumber").Value
                    '        objDrawing.Commit()

                    '    Catch ex As Exception
                    '        ' MessageBox.Show(ex.Message+vbNewLine+"重开图纸有错")
                    '        Writelog(objDrawing.Attributes("Name").Value + "    图纸更新Revision有错", "OpenDrawing")
                    '    End Try

                    '    Try
                    '        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(objDrawing.Attributes("Name").Value)
                    '        'Gap
                    '        objPID2d = objPIDAutoApp.Application.radapplication
                    '        AutoGap.GapAll(objPID2d)

                    '    Catch  '如果设置为后台开，好像就不会抱错了
                    '        objPIDADrawing = objPIDAutoApp.ActiveDrawing   '.NET上，上一句运行后，虽然图纸能打开，但是会抱错，所以加了这一句
                    '        'Gap
                    '        AutoGap.GapAll(objPIDAutoApp)

                    '    End Try

                    '    If objPIDADrawing Is Nothing Then
                    '        Writelog(objDrawing.Attributes("Name").Value + "    图纸未能打开", "OpenDrawing")
                    '    Else
                    '        '            objPIDADrawing.Save()
                    '        objPIDADrawing.CloseDrawing(True)
                    '        Writelog(objDrawing.Attributes("Name").Value + "    图纸打开,且进行了AutoGap", "OpenDrawing")
                    '    End If
                    'Else
                    '    Writelog(objDrawing.Attributes("Name").Value + "    图纸已打开过，无须打开", "OpenDrawing")
                    'End If
                Else
                    DrawingOpenCount = DrawingOpenCount + 1

                    '属性更新，后面再打开图纸  '打开图纸的同时，把属性传递下。Revision给Title Block Revision。
                    'objDrawing.Attributes("Revision").Value = objDrawing.Revisions.Nth(objDrawing.Revisions.Count).Attributes("SP_MajorRevisionNumber").Value +
                    '                          objDrawing.Revisions.Nth(objDrawing.Revisions.Count).Attributes("SP_MinorRevisionNumber").Value
                    'objDrawing.Commit()
                    '没必要了，revision属性的更新，已经在DrawingProp.vb的
                    'DrawingNumberBatchUpdate(Phase As String, Discipline As String, DWxxx As String, Mode As String, IfSPF As String)     过程下执行了


                    Try
                        objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(dtCreate(i)(0))
                        'Gap 自动断线
                        objPID2d = objPIDAutoApp.Application.radapplication
                        'AutoGap.GapAll(objPID2d)    '2020 12 07，陈玉娟取消断线


                    Catch  '如果设置为后台开，好像就不会抱错了
                        Try
                            objPIDADrawing = objPIDAutoApp.ActiveDrawing   '.NET上，上一句运行后，虽然图纸能打开，但是会抱错，所以加了这一句
                        Catch ex As Exception
                            objPIDAutoApp = Nothing
                            objPIDAutoApp = CreateObject("pidautomation.Application")
                            objPIDAutoApp.Visible = False
                            objPIDADrawing = objPIDAutoApp.ActiveDrawing
                        End Try

                        'Gap
                        'objPID2d = objPIDAutoApp.Application.radapplication
                        'AutoGap.GapAll(objPID2d)

                    End Try

                    If objPIDADrawing Is Nothing Then
                        Writelog(dtCreate(i)(0) + "    图纸未能打开", "OpenDrawing")
                    Else
                        '            objPIDADrawing.Save()
                        Try
                            objPIDADrawing.CloseDrawing(True)
                        Catch ex As Exception
                            Writelog(dtCreate(i)(0) + "    图纸打开,但未正常关闭", "OpenDrawing")
                        End Try

                        Writelog(dtCreate(i)(0) + "    图纸打开,并正确关闭", "OpenDrawing")   '原本是图纸打开，并进行AutoGap
                    End If
                End If

nextFOR:
                IntCount = IntCount + 1
                'ProgressBar1.Value = IntCount


            Next
            Try
                '    DS.CommitTransaction()
                objPIDAutoApp.Visible = True '可能会报错，但是对结果又没影响
            Catch
            End Try
            Dim audit As New audit(DS.ProjectNumber, "开图纸", "V1.0")
            audit.Add()
            audit = Nothing
            'objPIDAutoApp.Quit()
            'objPIDAutoApp = Nothing
            objPIDADrawing = Nothing
            'objDrawing = Nothing
            objDrawings = Nothing
            objHistories = Nothing
            'ProgressBar1.Value = 0
            'Sub_end(Me)
            MessageBox.Show("Open Drawings Finished." + vbNewLine + "Total " + DrawingOpenCount.ToString + " Of " + IntCount.ToString)
            IntCount = Nothing
            DrawingOpenCount = Nothing
            AutoGap = Nothing
            objPID2d = Nothing

        End If
    End Sub

    Private Sub RadMenuItem10_Click(sender As Object, e As EventArgs) Handles RadMenuItem10.Click
        'Sub_start(Me)

        Dim intResult As Integer
        intResult = MessageBox.Show("第一次运行时，会有一段时间的未相应，请勿强制关闭工具。", "Warning！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)

        If intResult = DialogResult.OK Then


            Dim insul1 = 0 : Dim insul2 = 0 : Dim insul3 = 0   '记录成功、失败的个数

            Dim oXML As XmlDocument  '用于和snecpid.dll的参数传递
            Dim InsulSpec As Object, InsulMat As Object, InsulThkSource As Object, InsulThk As Object, InsuDensity As Object  '用于和snecpid.dll的参数传递
            Dim GetInsulInfo As Object = New Object
            Dim oItems As LMAItems   '用于和snecpid.dll的参数传递
            Dim sPropertyName As String = "InsulPurpose" '用于和snecpid.dll的参数传递
            Dim vValue As Object '用于和snecpid.dll的参数传递

            Dim insuCount As Integer
            Dim insuTotalCount As Integer

            Dim sDrawingName As String
            Dim sLogOriginValue As String
            Dim sLogNewValue As String     'snecpid.dll计算返回值
            Dim sLogPRValue As String    '执行后的新值

            Dim HasError As Boolean = False
            Dim bRefreshCmd As Boolean = True
            Dim sInsulValID As String = "SNECPID.cGetInsulInfo"        '对应数据字典中相关 属性的ProgID或者CalcID

            Dim objFilter As LMAFilter
            Dim objPipeRuns As LMPipeRuns
            Try
                Try
                    GetInsulInfo = CreateObject(sInsulValID)    'snecpid.dll必须先要注册过才行
                Catch ex As Exception
                    MessageBox.Show("无法运行，确认是否正确注册了SNECPID.dll")
                    Exit Sub
                End Try

                oXML = New XmlDocument
                oXML.Load(sInsulFilePath)  'path在MainForm Load时就读入了

                Dim objDrawings As New LMDrawings
                GetDwgCol(DS, DrawingCol, objDrawings)

                For Each objDrawing As LMDrawing In objDrawings
                    sDrawingName = objDrawing.Attributes("Name").Value  '图纸的Name


                    objFilter = New LMAFilter
                    With objFilter
                        .ItemType = "PipeRun"
                        .Criteria.AddNew("1")
                        .Criteria.Item("1").SourceAttributeName = "Representation.Drawing.Name"
                        .Criteria.Item("1").ValueAttribute = sDrawingName
                        .Criteria.Item("1").Operator = "="

                        .Criteria.AddNew("2")
                        .Criteria.Item("2").SourceAttributeName = "ItemStatus"
                        .Criteria.Item("2").ValueAttribute = "1"
                        .Criteria.Item("2").Operator = "="
                        .Criteria.Item("2").Conjunctive = True

                        '.Criteria.AddNew("3")
                        '.Criteria.Item("3").SourceAttributeName = "PipeRunClass"
                        '.Criteria.Item("3").ValueAttribute = "2"   '不等于Instrument线
                        '.Criteria.Item("3").Operator = "!="
                        '.Criteria.Item("3").Conjunctive = True
                    End With

                    objPipeRuns = New LMPipeRuns
                    objPipeRuns.Collect(DS, Filter:=objFilter) '每张图纸下的piperuns
                    objFilter = Nothing
                    insuTotalCount = objPipeRuns.Count
                    'ProgressBar1.Maximum = insuTotalCount
                    'ProgressBar1.Minimum = 0
                    insuCount = 0

                    For Each oPipeRun As LMPipeRun In objPipeRuns  '每张图纸下的piperun
                        My.Application.DoEvents()            '让界面不会死在那里，可以执行其他操作
                        oItems = New LMAItems
                        oItems.Add(oPipeRun.AsLMAItem)
                        vValue = oPipeRun.Attributes(sPropertyName).Value
                        sLogOriginValue = oPipeRun.Attributes("InsulationSpec").Value & "/" & oPipeRun.Attributes("InsulType").Value _
                   & "/" & oPipeRun.Attributes("InsulThick").Value & "/" & oPipeRun.Attributes("InsulDensity").Value

                        GetInsulInfo = CreateObject(sInsulValID)
                        InsulSpec = "" : InsulMat = "" : InsulThkSource = "" : InsulThk = "" : InsuDensity = ""
                        GetInsulInfo.GetInsulInfo(bRefreshCmd, oXML, DS, oItems, sPropertyName, vValue, InsulSpec, InsulMat, InsulThkSource, InsulThk, InsuDensity)  '进行计算，之后InsulThk这几个值就直接存放结算结果了
                        GetInsulInfo = Nothing
                        oItems = Nothing


                        sLogNewValue = InsulSpec & "/" & InsulMat & "/" & InsulThk & "/" & InsuDensity

                        If sLogOriginValue = sLogNewValue Then
                            'No Need to Change
                            Writelog("No Need to Change     " + oPipeRun.Attributes("ItemTag").Value.ToString, "Insulation")
                            insul1 = insul1 + 1
                        Else
                            'With oPipeRun
                            '    .Attributes("InsulationSpec").Value = InsulSpec
                            '    .Attributes("InsulType").Value = InsulMat
                            '    .Attributes("InsulationThkSource").Value = InsulThkSource
                            '    .Attributes("InsulThick").Value = InsulThk
                            '    .Attributes("InsulDensity").Value = InsuDensity
                            '    .Commit()
                            'End With
                            DS.BeginTransaction()
                            oPipeRun.Attributes("InsulationThkSource").Value = "Software"
                            oPipeRun.Commit()
                            DS.CommitTransaction()

                            sLogPRValue = oPipeRun.Attributes("InsulationSpec").Value & "/" & oPipeRun.Attributes("InsulType").Value _
                                & "/" & oPipeRun.Attributes("InsulThick").Value & "/" & oPipeRun.Attributes("InsulDensity").Value

                            If sLogNewValue = sLogPRValue Then
                                'Update Successful
                                Writelog("Update Successful     " + oPipeRun.Attributes("ItemTag").Value.ToString + vbNewLine +
                                         "  Old Value" + sLogOriginValue + vbNewLine +
                                         "  New Value" + sLogNewValue, "Insulation")
                                insul2 = insul2 + 1

                            ElseIf sLogNewValue <> sLogPRValue Then
                                'Update Error
                                Writelog("Update Error" + oPipeRun.Id.ToString + "  " + oPipeRun.Attributes("ItemTag").Value.ToString + vbNewLine +
                                         "  Old  Value" + sLogOriginValue + vbNewLine +
                                         "  Calc Value" + sLogNewValue + vbNewLine +
                                         "  New  Value" + sLogPRValue, "Insulation")
                                insul3 = insul3 + 1

                                HasError = True
                            End If
                        End If

                        insuCount = insuCount + 1
                        'ProgressBar1.Value = insuCount

                    Next

                    objPipeRuns = Nothing
                Next


                If HasError Then
                    MessageBox.Show("Done" + vbNewLine +
                                    "无需更新:" + insul1.ToString + vbNewLine +
                                    "成功更新:" + insul2.ToString + vbNewLine +
                                    "更新失败:" + insul3.ToString)
                    Microsoft.VisualBasic.Shell("notepad.exe " + sInsulFilePath.Replace("InsulationSpec.isl", "SNECLog\InsulationLog - " + Environment.UserName + ".log"), vbNormalFocus)   '直接打开日志文件

                Else
                    MessageBox.Show("Done" + vbNewLine +
                                    "无需更新:" + insul1.ToString + vbNewLine +
                                    "成功更新:" + insul2.ToString)
                End If
                'ProgressBar1.Value = 0
                Dim audit As New audit(DS.ProjectNumber, "保温属性更新", "V1.0")
                audit.Add()
                audit = Nothing
                oXML = Nothing
                objDrawings = Nothing
            Catch
                MessageBox.Show("无法运行，请检查PID环境")
            End Try
        Else

        End If
    End Sub

    ''' <summary>
    ''' 从菜单栏里呼出“图纸EDE”窗口
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadMenuItem9_Click(sender As Object, e As EventArgs) Handles RadMenuItem9.Click
        Dim hiddenWindows As DockWindow() = Me.RadDock1.DockWindows.GetWindows(DockState.Hidden)
        Dim EDEExist As Boolean = False
        For Each x As DockWindow In hiddenWindows
            If x.Name = "EDE" Then
                Dim audit As New audit(DS.ProjectNumber, "图纸属性批量修改", "V1.0")
                audit.Add()
                audit = Nothing
                x.Show()
                RadDock1.ActiveWindow = x
            End If
        Next

        hiddenWindows = Nothing


    End Sub

    Private Sub RadMenuItem13_Click(sender As Object, e As EventArgs) Handles RadMenuItem13.Click
        FixMovedOPCs()
    End Sub

    Private Sub RadMenuItem14_Click(sender As Object, e As EventArgs) Handles RadMenuItem14.Click
        DeleteWrongPipeLine()
    End Sub


    ''' <summary>
    ''' 查询按钮
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadMenuItem21_Click(sender As Object, e As EventArgs) Handles RadMenuItem21.Click
        LoadDrawingToEDE()
    End Sub


    ''' <summary>
    ''' 属性列表里改动
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadCheckedListBox1_ItemCheckedChanged(sender As Object, e As ListViewItemEventArgs) Handles 图纸EDE属性列表.ItemCheckedChanged
        CheckOrUncheckOneProp(e)
    End Sub
    ''' <summary>
    ''' 更新按钮
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadMenuItem22_Click(sender As Object, e As EventArgs) Handles RadMenuItem22.Click
        'Sub_start(Me, "")
        UpdateDrawingFromEDE()
    End Sub

    Private Sub RadMenuItem23_Click(sender As Object, e As EventArgs) Handles RadMenuItem23.Click
        DrawingNumberBatchProp.ShowDialog()
    End Sub

    ''' <summary>
    ''' 上下2个gridview的宽度同时变动
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadGridView1_ColumnWidthChanged(sender As Object, e As ColumnWidthChangedEventArgs) Handles RadGridView1.ColumnWidthChanged
        'Dim col As GridViewDataColumn = RadGridView1.Columns(e.ColumnIndex)
        If e.ColumnIndex > -1 Then
            RadGridView2.Columns(e.ColumnIndex).Width = RadGridView1.Columns(e.ColumnIndex).Width
        End If
    End Sub
    ''' <summary>
    ''' 上下2个gridview的宽度同时变动
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadGridView2_ColumnWidthChanged(sender As Object, e As ColumnWidthChangedEventArgs) Handles RadGridView2.ColumnWidthChanged
        'Dim col As GridViewDataColumn = RadGridView1.Columns(e.ColumnIndex)
        If e.ColumnIndex > -1 Then
            RadGridView1.Columns(e.ColumnIndex).Width = RadGridView2.Columns(e.ColumnIndex).Width
        End If
    End Sub

    Private Sub RadMenuItem19_Click(sender As Object, e As EventArgs) Handles RadMenuItem19.Click
        Dim id As Integer = Microsoft.VisualBasic.Shell(System.Windows.Forms.Application.StartupPath + "\sppid_ini_ps.exe")
        'Dim myprocess As Process = Process.GetProcessById(id)
        'ShowIniPs.ShowDialog()
    End Sub

    Private Sub RadMenuItem20_Click(sender As Object, e As EventArgs) Handles RadMenuItem20.Click
        ResetPassword_FORM.ShowDialog()
    End Sub

    Private Sub RadMenuItem8_Click(sender As Object, e As EventArgs) Handles RadMenuItem8.Click
        Dim hiddenWindows As DockWindow() = Me.RadDock1.DockWindows.GetWindows(DockState.Hidden)
        For Each x As DockWindow In hiddenWindows
            If x.Name = "反向数据流" Then
                x.Show()
                RadDock1.ActiveWindow = x
            End If
        Next
    End Sub



    ''' <summary>
    ''' 反向数据流，查询
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub RadMenuItem24_Click(sender As Object, e As EventArgs) Handles RadMenuItem24.Click
        Dim GridViewCol As New List(Of RadGridView)
        GridViewCol.Add(RadGridView3)
        GridViewCol.Add(RadGridView4)
        GridViewCol.Add(RadGridView5)
        GridViewCol.Add(RadGridView6)
        GridViewCol.Add(RadGridView7)
        ReadData(GridViewCol)

        'Me.RadProgressBarElement1.Value1 = 0
        'Me.RadProgressBarElement1.Text = "Done"

        For Each View In GridViewCol
            For Each c In View.Columns.AsEnumerable().Where(Function(X) X.Index > 0).ToList
                c.ReadOnly = True
                c.BestFit()

            Next

            For Each row In View.Rows
                For i = 0 To View.Columns.Count - 1 - 1

                    SetBackColorIfValuesDiff(row.Cells(i), row.Cells(i + 1))
                Next
            Next
        Next

        GridViewCol = Nothing
        MessageBox.Show("查询完毕。")
        Dim audit As New audit(DS.ProjectNumber, "反向数据流", "V1.0")
        audit.Add()
        audit = Nothing
    End Sub
    ''' <summary>
    ''' 在OOTB的右键菜单上，为右键菜单加新的按钮
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadGridView1_ContextMenuOpening1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ContextMenuOpeningEventArgs) Handles RadGridView2.ContextMenuOpening
        Dim customMenuItem As RadMenuItem = New RadMenuItem()
        customMenuItem.Text = "批量清空该列"
        Dim separator As RadMenuSeparatorItem = New RadMenuSeparatorItem()
        e.ContextMenu.Items.Add(separator)
        e.ContextMenu.Items.Add(customMenuItem)
        AddHandler customMenuItem.Click, AddressOf SetBatchDeletionFlg
    End Sub




    Private Sub RadMenuItem4_Click(sender As Object, e As EventArgs)
        RemoveHandler RadMenuItem4.Click, AddressOf RadMenuItem4_Click '解绑
        Dim mi As MethodInvoker = New MethodInvoker(AddressOf LongTimeSub)   '定义委托
        mi.BeginInvoke(Nothing, Nothing) '异步调用委托


        'RadMenuItem4.Enabled = False
    End Sub
    Private Delegate Sub ShowWaiting委托(ByVal ShowOrHide As Boolean) '委托，用于一些控件的操作。因为跨线程不能直接调用控件。

    Private Sub LongTimeSub() '   委托关联的sub，会在另一个线程中完成。且不会阻塞当前线程。

        Me.Invoke(New ShowWaiting委托(AddressOf ShowWaiting), True) 'me.text的显示也用了委托
        For i As Integer = 0 To 100
            Thread.Sleep(100)

            'Me.Invoke(New SubDelegate(AddressOf SetText), i.ToString & "%"）
        Next
        AddHandler RadMenuItem4.Click, AddressOf RadMenuItem4_Click '再次关联，这样在第一次点击并执行期间，第二次无法点击。
        'RadMenuItem4.Enabled = True   '对控件的交互，这样直接都不行，因为跨线程了。
        Me.Invoke(New ShowWaiting委托(AddressOf ShowWaiting), False)
    End Sub

    Private Sub ShowWaiting(ByVal ShowOrHide As Boolean)
        If ShowOrHide Then
            Waiting.Show()  'showdialog不行
            Waiting.TopMost = True
        Else
            Waiting.TopMost = False
            Waiting.Hide()
        End If
    End Sub

    ''' <summary>
    ''' 反向数据流，更新
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub RadMenuItem25_Click(sender As Object, e As EventArgs) Handles RadMenuItem25.Click
        Dim Mode As Integer
        MessageBox.Show("此功能涉及到阀门等Symbol的替换，需要进行re-create图纸，才能生效。" + vbNewLine + "更新范围为当前激活的sheet中，被选中的行。")
        Mode = 1
        'End If
        DrawingCol.Clear()
        Dim DwgIDs As String = ""
        GetDwgCol(DS, DrawingCol, DwgIDs)




        Dim GridViewCol As New List(Of RadGridView)
        GridViewCol.Add(RadGridView3)
        GridViewCol.Add(RadGridView4)
        GridViewCol.Add(RadGridView5)
        GridViewCol.Add(RadGridView6)
        GridViewCol.Add(RadGridView7)
        UpdateData(GridViewCol, Mode)


        GridViewCol = Nothing
        Dim audit As New audit(DS.ProjectNumber, "反向数据流", "V1.0")
        audit.Add()
        audit = Nothing
        MessageBox.Show("Done.更新日志，请查看共享文件夹下的SNECLog。")
    End Sub

    '删除云线
    Private Sub RadMenuItem27_Click(sender As Object, e As EventArgs) Handles RadMenuItem27.Click
        '得到选择的图纸
        UnitCol.Clear() : DrawingCol.Clear()
        LoopTreeNode(Me.RadTreeView1.Nodes.Item(0), DrawingCol, UnitCol)
        If DrawingCol.Count = 0 Then
            RadMessageBox.Show("Please Select drawings!")
            Exit Sub
        Else
            FrmDelRevCloud.ShowDialog()
        End If



    End Sub
    ''' <summary>
    ''' 查看日志文件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub RadMenuItem28_Click(sender As Object, e As EventArgs) Handles RadMenuItem28.Click
        Dim PDFPath As String = sInsulFilePath.Replace("InsulationSpec.isl", "SNECLog")
        If IO.Directory.Exists(PDFPath) Then
            System.Diagnostics.Process.Start("explorer.exe", PDFPath)
        End If

    End Sub

    Private Sub RadGridView3_CellDoubleClick(sender As Object, e As GridViewCellEventArgs) Handles RadGridView3.CellClick
        If e.ColumnIndex = 0 And e.RowIndex > -1 Then
            RadGridView3.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = Not e.Value   '双击勾选checkbox
        End If
    End Sub
    Private Sub RadGridView4_CellDoubleClick(sender As Object, e As GridViewCellEventArgs) Handles RadGridView4.CellClick
        If e.ColumnIndex = 0 And e.RowIndex > -1 Then
            RadGridView4.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = Not e.Value   '双击勾选checkbox
        End If
    End Sub
    Private Sub RadGridView5_CellDoubleClick(sender As Object, e As GridViewCellEventArgs) Handles RadGridView5.CellClick
        If e.ColumnIndex = 0 And e.RowIndex > -1 Then
            RadGridView5.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = Not e.Value   '双击勾选checkbox
        End If
    End Sub
    Private Sub RadGridView6_CellDoubleClick(sender As Object, e As GridViewCellEventArgs) Handles RadGridView6.CellClick
        If e.ColumnIndex = 0 And e.RowIndex > -1 Then
            RadGridView6.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = Not e.Value   '双击勾选checkbox
        End If
    End Sub
    Private Sub RadGridView7_CellDoubleClick(sender As Object, e As GridViewCellEventArgs) Handles RadGridView7.CellClick
        If e.ColumnIndex = 0 And e.RowIndex > -1 Then
            RadGridView7.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = Not e.Value   '双击勾选checkbox
        End If
    End Sub






    Private Sub RadGridView3_CellFormatting(sender As Object, e As CellFormattingEventArgs) Handles RadGridView3.CellFormatting
        If e.ColumnIndex = 0 Then
            e.Column.ReadOnly = False

        End If
    End Sub



    Private Sub RadMenuItem29_Click(sender As Object, e As EventArgs) Handles RadMenuItem29.Click

        If MessageBox.Show("该功能的作用是根据所选图纸来生成若干个图纸目录图纸。您需要指定图纸目录的名字、图号，所用图框，所在Unit。", "图纸目录", MessageBoxButtons.YesNo) = DialogResult.Yes Then
            DwgList.Show()

        End If

    End Sub

    Private Sub RadMenuItem7_Click(sender As Object, e As EventArgs) Handles RadMenuItem7.Click
        If MessageBox.Show("该功能的作用是根据S3D模型解析出来的拓扑关系，来自动生成对应的PID图纸。", "反向自动生成图纸", MessageBoxButtons.YesNo) = DialogResult.Yes Then
            Dim x As New PlotDrawingFrom3D()  '神奇，必须import才可以，不可以直接带出表空间 + 类名
            x.PIDDBConn = MyPIDConn
            Dim audit As New audit(DS.ProjectNumber, "自动绘制UID", "V1.0")
            audit.Add()
            audit = Nothing
            x.ShowDialog()

            'Dim y As New PlotDrawFromXml.MainWindow(MyPIDConn)
            'y.ShowDialog()
        End If
    End Sub

    Private Sub RadMenuItem30_Click(sender As Object, e As EventArgs) Handles RadMenuItem_propagateinstr.Click
        If IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\功能\3D属性传递\PropagateInstr.exe") Then
            Process.Start(System.Windows.Forms.Application.StartupPath + "\功能\3D属性传递\PropagateInstr.exe")
            Dim audit As New audit(DS.ProjectNumber, "3D属性传递", "V1.0")
            audit.Add()
            audit = Nothing
        Else
            MessageBox.Show("未找到" + System.Windows.Forms.Application.StartupPath + "\功能\3D属性传递\PropagateInstr.exe")
        End If

    End Sub

    Private Sub RadMenuItem_ExcelCompare_Click(sender As Object, e As EventArgs) Handles RadMenuItem_ExcelCompare.Click
        If IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\Excel相关\Excel对比\Excel Compare.exe") Then
            Process.Start(System.Windows.Forms.Application.StartupPath + "\Excel相关\Excel对比\Excel Compare.exe")
            Dim audit As New audit(DS.ProjectNumber, "Excel对比", "V1.0")
            audit.Add()
            audit = Nothing
        Else
            MessageBox.Show("未找到" + System.Windows.Forms.Application.StartupPath + "\Excel相关\Excel对比\Excel Compare.exe")
        End If
    End Sub

    Private Sub RadMenuItem_RefreshFluidCode_Click(sender As Object, e As EventArgs) Handles RadMenuItem_RefreshFluidCode.Click
        If IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\功能\介质名称中英文批量\RefreshFluidCode.exe") Then
            Process.Start(System.Windows.Forms.Application.StartupPath + "\功能\介质名称中英文批量\RefreshFluidCode.exe")
            Dim audit As New audit(DS.ProjectNumber, "介质名称中英文", "V1.0")
            audit.Add()
            audit = Nothing
        Else
            MessageBox.Show("未找到" + System.Windows.Forms.Application.StartupPath + "\功能\介质名称中英文批量\RefreshFluidCode.exe")
        End If
    End Sub

    Private Sub RadMenuItem18_Click(sender As Object, e As EventArgs) Handles RadMenuItem18.Click
        If IO.File.Exists(System.Windows.Forms.Application.StartupPath + "\功能\仪表回路自动编制\instrloopsautomation.exe") Then
            Process.Start(System.Windows.Forms.Application.StartupPath + "\功能\仪表回路自动编制\instrloopsautomation.exe")
            Dim audit As New audit(DS.ProjectNumber, "仪表回路自动编制", "V1.0")
            audit.Add()
            audit = Nothing
        Else
            MessageBox.Show("未找到" + System.Windows.Forms.Application.StartupPath + "\功能\仪表回路自动编制\instrloopsautomation.exe")
        End If
    End Sub

    Private Sub RadMenuItem31_Click(sender As Object, e As EventArgs) Handles RadMenuItem31.Click
        Dim PDFPath As String
        PDFPath = System.Windows.Forms.Application.StartupPath & "\使用说明.PDF"
        Dim PDFProcess As System.Diagnostics.Process
        Try
            PDFProcess = New System.Diagnostics.Process
            PDFProcess.StartInfo.FileName = PDFPath
            PDFProcess.Start()
        Catch ex As Exception

            MessageBox.Show("无法打开帮助文档，请检查本机是否安装了PDF")
        End Try
    End Sub

    Private Sub RadMenuItem32_Click(sender As Object, e As EventArgs) Handles RadMenuItem32.Click
        Dim PDFPath As String
        PDFPath = System.Windows.Forms.Application.StartupPath & "\功能\快捷键\快捷键配置方式及使用说明.PDF"
        Dim PDFProcess As System.Diagnostics.Process

        If IO.File.Exists(PDFPath) Then
            Try
                PDFProcess = New System.Diagnostics.Process
                PDFProcess.StartInfo.FileName = PDFPath
                PDFProcess.Start()
            Catch ex As Exception
                MessageBox.Show("无法打开帮助文档，请检查本机是否安装了PDF")
            End Try
        Else
            MessageBox.Show("未找到" + PDFPath)
        End If


    End Sub

    Private Sub RadMenuItem30_Click_1(sender As Object, e As EventArgs) Handles RadMenuItem30.Click

        System.Windows.MessageBox.Show("该功能需要配合PID主程序（draft.exe）。确保您已经保存了正在编辑中的图纸。")

        Do
            Dim ps = System.Diagnostics.Process.GetProcessesByName("draft")
            If ps.Length > 0 Then
                System.Windows.MessageBox.Show("你需要保存并关闭正在修改的图纸。")
            Else
                Exit Do
            End If
        Loop
        Dim dsResult As DataSet = New DataSet() '用于在result.vb里
        '步骤1，选图纸
        Dim objDrawings As New LMDrawings
        GetDwgCol(DS, DrawingCol, objDrawings)

        Dim x2 As New QualityCheck.Main(MyPIDConn, objDrawings)
        dsResult = x2.Start()
        Dim RES2 As New Result(dsResult)
        RES2.ShowDialog()

        x2 = Nothing
    End Sub

    Private Sub RadGridView1_Click(sender As Object, e As EventArgs) Handles RadGridView1.Click

    End Sub

    Private Sub RadMenuItem33_Click(sender As Object, e As EventArgs) Handles RadMenuItem33.Click
        'Dim objDrawings As LMDrawings
        'DrawingCol.Clear() : UnitCol.Clear()
        'LoopTreeNode(Me.RadTreeView1.Nodes.Item(0), DrawingCol, UnitCol)
        'objDrawings = New LMDrawings
        'Dim objPID2d As Ingr.RAD2D.Interop.RAD2D.Application
        'Dim objPIDAutoApp As InteropPidAuto.Application
        'Dim objPIDADrawing As InteropPidAuto.Drawing

        'objPIDAutoApp = CreateObject("pidautomation.Application")
        'Dim DwgIDs As String = ""
        'If DrawingCol.Count = 0 Then
        '    MessageBox.Show("未选中任一图纸")
        '    Exit Sub
        'End If

        'GetDwgCol(DS, DrawingCol, objDrawings)

        'For Each objDrawing As LMDrawing In objDrawings
        '    objPIDADrawing = objPIDAutoApp.Drawings.OpenDrawing(objDrawing.Name)
        '    Dim a As New SetDisplaySet
        '    a.SetDisplaySet(True)
        '    Dim place As New Placement
        '    'Dim strProj As String = place.PIDDataSource.ProjectNumber
        '    Dim pidMgr As InteropIPidObjectManagerInf.IPidObjectManager = place.PIDDataSource.PIDMgr
        '    Dim dwg As Ingr.SP2D.ISPItem = pidMgr.Drawing
        '    Dim radApp As rad2d.Application = pidMgr.Application.RADApplication
        '    Dim strPDFName As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/" + dwg.Attributes("Name").Value + ".PDF" ' CStr(group)
        '    radApp.ActiveDocument.SaveAsPDF(strPDFName, False, rad2d.PDFResolutionConstants.igPDFResolution300DPI, rad2d.PDFColorModeConstants.igPDFColorModeColor, rad2d.PDFJpegCompressionConstants.igPDFJpegGoodQualityGoodCompression, 0, Nothing)
        '    a.SetDisplaySet(False)
        '    objPIDADrawing.CloseDrawing(True)

        'Next
        'MessageBox.Show("Done")
    End Sub
End Class
